import os
import sys

# Analytics function 编码器
class AnalyticsFunctionCoder:

        # const fileds
        FUNC_FILE_PATH = '../../Iteration/VersionHolder/Generated/analytics/AnalyticsMgr.cs'
        FUNC_CLASS_SIGN = 'public static class AnalyticsMgr'
        HEAD_SIGN = 'public static void SendAnalytics_{0}({1})\n'
        USING_AREA = 'using System.Collections.Generic;\nusing LitJson;\n\n'
        DIC_SIGN = '\tprivate static readonly Dictionary<string, object> _pushDic = new Dictionary<string, object>();\n\n'
        DIC_BASE_ITEM_SIGN = '\t\t_pushDic["{0}"] = {0};\n'
        DIC_COLLECTION_ITEM_SIGN = '\t\tif ({0}.Count > 0)\n\t\t{{\n\t\t\t_pushDic["{0}"] = {0};\n\t\t}}\n'
        SEND_METHOD_SIGN = '\t\t//SDKManager.Instance.analyticsMgr.SendPoint({0}, JsonMapper.ToJson(_pushDic));\n'

         #field
        _lvEventNameArr = ["g_level_start", "g_revive", "g_level_win", "g_level_fail", "g_level_quit"]
        _lvCommonObjectParmsArr = ["g_o_star_times", "g_model_detail", "g_o_return_level", "g_o_purchase_level", "g_o_used_item", "g_bar_detail", "g_o_collect_detail"]

        #construction
        def __init__(self):
                self._strBuilder = self.USING_AREA
                self._strBuilder += self.FUNC_CLASS_SIGN
                self._strBuilder += '\n'
                self._strBuilder += '{\n'
                self._strBuilder += self.DIC_SIGN

               
        # function
        def GenerateSingleFunction(self, event_name, filed_type_list, filed_name_list):
                field_strs = ''
                count = len(filed_type_list)
                field_name_list = []
                mid_object_group_flag = False
                collection_list = []
                for index in range(0, count):
                        field_name = filed_name_list[index]
                        if self.IsObjectStruct(field_name):
                                continue
                        field_type = filed_type_list[index]
                        parse_type = self.ParseFiledType(field_type, event_name, field_name)
                        if parse_type == None:
                                continue
                        else:
                                field_strs += f"{parse_type} "

                        field_name_list.append(field_name) 
                        if field_type == "对象组" or field_type == "列表":
                                collection_list.append(field_name)
                        
                        if index < count - 1:
                                if field_type == '对象组':
                                       mid_object_group_flag = True 
                                field_strs += f"{field_name}, "
                        else:
                                mid_object_group_flag = False
                                field_strs += f"{field_name}"
                        
                if mid_object_group_flag:
                        field_strs = field_strs[:-2]

                content = self.HEAD_SIGN.format(event_name, field_strs)
                content += '\t{\n'
                content += '\t\t_pushDic.Clear();\n'
                for f_name in field_name_list:
                        if self.IsCollectionType(f_name, collection_list):
                                content += self.DIC_COLLECTION_ITEM_SIGN.format(f_name)
                        else:
                                content += self.DIC_BASE_ITEM_SIGN.format(f_name)

                content += self.SEND_METHOD_SIGN.format(f'AnalyticsEventDefine.{event_name}_event_name')
                content += '\t}'
                return content
        
        # 是否是集合类型
        def IsCollectionType(self, field_name, collection):
                return field_name in collection
        
        # 解析字段类型
        def ParseFiledType(self, t, event_name, filed_name):
                if t == '字符串':
                        return 'string'
                if t == '数值':
                        return 'int'
                if t == '对象组':
                        if event_name in self._lvEventNameArr and filed_name in self._lvCommonObjectParmsArr:
                                return f"List<{filed_name}>"
                        else:
                                return f"List<{event_name}_{filed_name}>"
                if t == '布尔':
                        return 'bool'
                if t == '列表':
                        return 'List<string>'
                return None
        
        # 判断是否是对象类型
        def IsObjectStruct(self, field_name):
                if type(field_name) is str:
                        arr = field_name.split('.')
                        if len(arr) > 1:
                                return True
                return False
        
        # 输出到文件
        def SaveAllFuncs(self, func_str_arr, version):
                count = len(func_str_arr)
                for index in range(0, count):
                        single_str = func_str_arr[index]
                        self._strBuilder += f"\t{single_str}"
                        if index == count - 1:
                                self._strBuilder += '\n'
                        else:
                                self._strBuilder += '\n\n'
                self._strBuilder += '}'

                # 路径替换正确的版本
                self.FUNC_FILE_PATH = self.FUNC_FILE_PATH.replace("VersionHolder", version)
                self.FUNC_FILE_PATH = os.path.abspath(self.FUNC_FILE_PATH)
                # 确保目录存在
                target_dir = os.path.dirname(self.FUNC_FILE_PATH)
                if not os.path.exists(target_dir):
                        os.makedirs(target_dir, exist_ok=True)  # 递归创建目录

                with open(self.FUNC_FILE_PATH, 'w') as f:
                        f.write(self._strBuilder)
                print(f"### {self.FUNC_FILE_PATH} write success !!!")
